﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Sinacor.Infra.Core.Licensing.Business;


namespace WebLicenseGenerator.UC
{
	public enum InputResult
	{
		Save = 1,
		Cancel = 2
	}

	public class InputEventArgs
	{
		InputResult _result;
		public InputResult Result
		{
			get { return _result; }
			set { _result = value; }
		}

		public InputEventArgs(InputResult result)
		{
			_result = result;
		}
	}

	public partial class CompanyInput : System.Web.UI.UserControl
	{
		Empresa _companyBusiness;
		public event InputEventHandler OnAction;
		public delegate void InputEventHandler(object sender, InputEventArgs e);

		public string Title
		{
			get { return lblInputTitle.Text; }
			set { lblInputTitle.Text = value.ToUpper(); }
		}
		
		public string Message
		{
			get { return lblInputMessage.Text; }
			set { lblInputMessage.Text = value; }
		}

		public int CompanyId
		{
			get
			{
				if (ViewState["CompanyInputCompanyId"] != null)
					return Convert.ToInt32(ViewState["CompanyInputCompanyId"]);
				else
					return 0;
			}
			set { ViewState["CompanyInputCompanyId"] = value; }
		}

		public string CompanyName
		{
			get { return txtCompanyName.Text; }
			set { txtCompanyName.Text = value; }
		}

		public string CompanyCNPJ
		{
			get { return txtCNPJ.Text; }
			set { txtCNPJ.Text = value; }
		}

		public string CompanySinacorId
		{
			get { return txtCompanySinacorID.Text; }
			set { txtCompanySinacorID.Text = value; }
		}

        protected void Page_Load(object sender, EventArgs e)
        {
		}

		protected void btOk_Click(object sender, EventArgs e)
		{
			if (this.ValidateFields())
			{
				Sinacor.Infra.Core.Licensing.Company company = new Sinacor.Infra.Core.Licensing.Company();
				company.CompanyId = this.CompanyId;
				company.Name = txtCompanyName.Text.Trim();
				company.LegalRegistrationId = this.txtCNPJ.Number.Trim();
				company.SinacorCompanyId = Convert.ToInt32(this.txtCompanySinacorID.Text.Trim());

				_companyBusiness = new Empresa();
				_companyBusiness.Alterar(company);

				if (OnAction != null)
					OnAction(this, new InputEventArgs(InputResult.Save));

				this.HideInputDialog();
			}
			else
				this.ShowInputDialog();
		}

		protected void btCancel_Click(object sender, EventArgs e)
		{
			if (OnAction != null)
				OnAction(this, new InputEventArgs(InputResult.Cancel));

			this.HideInputDialog();
		}

		public void ShowInputDialog()
		{
			mpe.Show();
		}

		public void HideInputDialog()
		{
			mpe.Hide();
		}

		bool ValidateFields()
		{
			return (txtCompanyName.IsValid && txtCNPJ.IsValid && txtCompanySinacorID.IsValid);
		}
	}
}